﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DevExpress.Web.Mvc;
using Webcar.BLL;
using Webcar.Entitys;
using Webcar.Utils;
using System.Data.Entity;
using System.Web.UI.WebControls;
using System.Threading;
using System.Data;
using EntityFramework.Extensions;
namespace Webcar.Controllers
{

    public partial class InsureController : BaseControler
    {
        [HttpGet]
        public ActionResult List()
        {
            ViewBag.ShowOptions = new ShowInsureOptions();
            HttpContext.Session["ShowInsureOptions"] = ViewBag.ShowOptions;
            return View();
        }
        [HttpPost]
        public ActionResult List(ShowInsureOptions options)
        {
            ViewBag.ShowOptions = options;
            HttpContext.Session["ShowInsureOptions"] = options;
            return View();
        }
        public ActionResult ListPartialView()
        {
            ViewBag.ShowOptions = new ShowInsureOptions();
            return PartialView();
        }
        [HttpGet]
        public ActionResult Edit(string id,string dept,bool is_continue)
        {
            BS_INSURE insure = null;
            if (id.IsNotNull())
            {
                insure = WebcarDataProvider.DB.BS_INSURE.Find(id);
                if (is_continue)
                {
                    BS_INSURE newinsure = new BS_INSURE();
                    insure.CopyPropertyTo(newinsure);
                    newinsure.START_DATE = insure.END_DATE;
                    newinsure.END_DATE = insure.END_DATE.Value.AddYears(1);
                    newinsure.INSURE_NO2 = null;
                    newinsure.INSURE_NO = null;
                    insure = newinsure;
                }
            }
            if (insure == null)
            {
                insure = new BS_INSURE();
                insure.DEPT_CODE = dept;
            }
            ViewBag.RecordNo = null;
            if (insure.CAR_NO.IsNotNull())
            {
                var car = WebcarDataProvider.DB.BS_CAR_RECORD.Find(insure.CAR_NO);
                if (car != null)
                {
                    ViewBag.RecordNo = car.RECORD_NO;
                }
            }
            return View(insure);
        }

        public ActionResult Export()
        {
            GridViewSettings settings = new GridViewSettings();
            settings.Name = "gridView";
            settings.KeyFieldName = "INSURE_NO";
            settings.AddDeptColumn();
            settings.Columns.Add("RECORD_NO", "牌照号");
            settings.Columns.Add("INSURE_NO2", "保险单号");
            settings.Columns.Add("START_DATE", "保险开始日期", MVCxGridViewColumnType.DateEdit).PropertiesEdit.DisplayFormatString = "yyyy-MM-dd";
            settings.Columns.Add("END_DATE", "保险到期日期", MVCxGridViewColumnType.DateEdit).PropertiesEdit.DisplayFormatString = "yyyy-MM-dd";
            settings.Columns.Add("INSURE_MONEY", "保险金额");
            settings.Columns.Add("STATUS", "保险单状态").CellStyle.HorizontalAlign = HorizontalAlign.Center;
            var data = UserDataProvider.GetInsureList(this.RouteData).ToDataTable();
            return GridViewExtension.ExportToXls(settings, data, "保险单");

            //return RedirectToAction("List", "Car");
        }

        bool CheckInsureModel(BS_INSURE model, ref string error)
        {
            if (model.CAR_NO.IsNull())
            {
                error = "请选择车辆。";
                return false;
            }
            if (model.INSURE_NO2.IsNull())
            {
                error = "请输入保险单号。";
                return false;
            }
            if (model.JQX_NO.IsNull())
            {
                error = "请输入交强险号。";
                return false;
            }
            if (model.DEPT_CODE.IsNull())
            {
                error = "请输入车辆所属单位。";
                return false;
            }
            if (model.INSURE_MONEY <= 0)
            {
                error = "请输入保险总金额。";
                return false;
            }
            if (model.FIRST_DATE.IsNull())
            {
                error = "请输入初次登记日期。";
                return false;
            }
            if (model.START_DATE==null)
            {
                error = "请输入保险开始日期。";
                return false;
            }
            if (model.END_DATE==null)
            {
                error = "请输入保险结束日期。";
                return false;
            }
            if (model.END_DATE < model.START_DATE)
            {
                error = "保险结束日期必须小于开始日期。";
                return false;
            }
            return true;
        }
        [HttpPost]
        public ActionResult Edit(BS_INSURE model)
        {
            CurrentUser.EnsurePermission(PermissionManager.编辑车辆保险);
            try
            {
                string error = "";
                if (this.CheckInsureModel(model, ref error) == false)
                {
                    ViewBag.ErrorMessage = error;
                    return View(model: model);
                }
                BS_INSURE item = null;
                using (var DB = new WebcarContext())
                {
                    if (model.INSURE_NO.IsNotNull())
                    {
                        item = DB.BS_INSURE.Find(model.INSURE_NO);
                    }
                    else
                    {
                        item = new BS_INSURE();
                        DB.BS_INSURE.Add(item);
                        //item.IS_USE = "T";
                    }
                    model.CopyPropertyTo(item);
                    if (item.INSURE_NO.IsNull())
                        item.INSURE_NO = "I" + DB.GetSearialId();
                    if (item.RECORD_NO.IsNull())
                        item.RECORD_NO = "no_need";
                    DB.SaveChanges();
                }
                var car = WebcarDataProvider.DB.BS_CAR_RECORD.Find(model.CAR_NO);
                if (car != null)
                {
                    return RedirectToAction("List", "Insure", new { id = model.DEPT_CODE,type=car.IsMoto?"Moto":"Default"});
                }
                else
                {
                    return RedirectToAction("List", "Insure", new { id = model.DEPT_CODE });
                }
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMessage = ex.Message;
                return View(model: model);
            }
        }
        public ActionResult Summary(string year, string type)
        {
            if (year.IsNull()) return View();
            string sql = @"select c.deptname,SUM(insure_money) month_all,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-01' then isnull(a.insure_money,0) else 0 end) month_01,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-02' then isnull(a.insure_money,0) else 0 end) month_02,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-03' then isnull(a.insure_money,0) else 0 end) month_03,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-04' then isnull(a.insure_money,0) else 0 end) month_04,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-05' then isnull(a.insure_money,0) else 0 end) month_05,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-06' then isnull(a.insure_money,0) else 0 end) month_06,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-07' then isnull(a.insure_money,0) else 0 end) month_07,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-08' then isnull(a.insure_money,0) else 0 end) month_08,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-09' then isnull(a.insure_money,0) else 0 end) month_09,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-10' then isnull(a.insure_money,0) else 0 end) month_10,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-11' then isnull(a.insure_money,0) else 0 end) month_11,
                     sum(case convert(varchar(7),a.start_date,120) when '{0}-12' then isnull(a.insure_money,0) else 0 end) month_12
                     from BS_INSURE a,BS_CAR_RECORD b,sys_dept c
                      where a.CAR_NO=b.CAR_NO and a.DEPT_CODE=c.deptcode
                      and c.use_flag='T' {1}
                      and convert(varchar(4),a.start_date,120)='{0}'
                    group by c.deptname";
            if (type == "moto")
            {
                sql = sql.FormatWith(year," and b.car_sort='52' ");
            }
            else if (type == "not_moto")
            {
                sql = sql.FormatWith(year," and b.car_sort<>'52' ");
            }
            else
            {
                sql = sql.FormatWith(year,"");
            }

            

            DataTable table = WebcarDataProvider.DB.ExecuteDataTable(sql);
            return View(model: table);
        }
        public ActionResult Delete(string id,string deptcode)
        {
            CurrentUser.CheckPermission(PermissionManager.编辑车辆保险);
            using (var DB = new WebcarContext())
            {
                DB.BS_INSURE.Delete(a => a.INSURE_NO == id);
                DB.SaveChanges();
            }
            return RedirectToAction("List", "Insure", new { id = deptcode });
        }
    }

    public class ShowInsureOptions
    {
        public ShowInsureOptions()
        {
            this.ShowLast = false;
        }
        public bool ShowLast
        {
            get;
            set;
        }
    }
}